--[[
	系统级别的日志，主要是重定向了skynet本身的log
	也按节点明存放在applog的目录下，不按天切割。
	每次启动都新增一个，方便查找问题，而不是原来每次启动去覆盖
	参照了 官方 example 里的 userlog
	]]
local skynet = require "skynet"
require "skynet.manager"
local configtool = require "configtool"
local timetool = require "timetool"
local os = os

local nodename = "anonynode"
local current_time = "20170901_000000"

local logfilename = "./systemlog"

skynet.register_protocol {
	name = "text",
	id = skynet.PTYPE_TEXT,
	unpack = skynet.tostring,
	dispatch = function(_, address, msg)
		write_log(address, msg)
		-- print(string.format(":%08x(%.2f): %s", address, skynet.time(), msg .. "_" .. nodename))
	end
}

skynet.register_protocol {
	name = "SYSTEM",
	id = skynet.PTYPE_SYSTEM,
	unpack = function(...) return ... end,
	dispatch = function()
		-- reopen signal
		print("SIGHUP")
	end
}

function write_log(address, msg)
	local f = io.open(logfilename, "a+")
	if not f then
		print("Path: ../../applog  not exist")
		skynet.abort()
	end
	local tmpstr = string.format("%s:[%08x]: %s", os.date("%m%d_%H%M%S", timetool.get_time()), address, msg)
	-- 跳过打印显示agent的启动信息，因为agent会配置上千个。
	if (skynet.getenv("runtime") ~= "r"
		or msg:sub(1, 18) ~= 'LAUNCH snlua agent') then
			print(tmpstr)
	end

	f:write(tmpstr)
	f:write("\n")
	f:close()
end

skynet.start(function()
	local log_path = skynet.getenv("logpath")
	local file = io.open(log_path, "rb")
	if file then
		file:close()
	else
		os.execute("mkdir -p "..log_path)
	end

	logfilename = skynet.getenv("logpath") .. "/" .. 
				(configtool.load_config(skynet.getenv("node_config"))['nodename'] or "anonynode") .. "_" .. 
				os.date("%Y%m%d_%H%M%S", timetool.get_time()) .. ".log"
	skynet.register ".logger"
end)